package com.wbs.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wbs.api.AddrAPI;
import com.wbs.api.CartAPI;
import com.wbs.api.ItemAPI;
import com.wbs.config.IdWorker;
import com.wbs.mapper.TbOrderItemMapper;
import com.wbs.mapper.TbOrderMapper;
import com.wbs.model.TbAddress;
import com.wbs.model.TbItem;
import com.wbs.model.TbOrder;
import com.wbs.model.TbOrderItem;
import com.wbs.service.OrderService;
import com.wbs.utils.JwtUtil;
import com.wbs.vo.CartVO;
import com.wbs.vo.DetailVO;
import com.wbs.vo.PayVo;
import com.wbs.vo.UserVO;
import io.jsonwebtoken.Claims;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 芝梦
 * @Description: 订单服务层
 * @DateTime: 2024/2/27 18:00
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private TbOrderMapper tbOrderMapper;

    @Autowired
    private CartAPI cartAPI;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private AddrAPI addrAPI;

    @Autowired
    private ItemAPI itemAPI;

    @Autowired
    private TbOrderItemMapper tbOrderItemMapper;

    //@Transactional 智能控制单体事务, 控制不了分布式事务  也就是说远程调用的接口无法事务处理
//    @Transactional
    //@GlobalTransactional 控制分布式事务
    @GlobalTransactional
    @Override
    public PayVo submitOrder(String token, String paymentType, Long addrId) {
        //获取购物车信息
        List<CartVO> cartList = cartAPI.getCatList(token);

        //解析用户信息
        Claims claims = jwtUtil.parseJwt(token);
        String subject = claims.getSubject();
        UserVO userVO = JSONObject.parseObject(subject, UserVO.class);

        //根据id获取地址信息
        TbAddress address = addrAPI.selectAddrById(addrId);

        //定义存储for产生的订单和明细数据集合
        ArrayList<TbOrder> orders = new ArrayList<>();
        ArrayList<TbOrderItem> items = new ArrayList<>();
        //定义集合存储需要扣减存库的数量以及商品的id
        ArrayList<TbItem> counts = new ArrayList<>();
        
        //定义支付金额
        BigDecimal payMoney = new BigDecimal(0);
        
        //定义支付名称
        StringBuilder sb = new StringBuilder();

        //遍历
        for (CartVO cartVO : cartList) {
            TbOrder order = new TbOrder();
            order.setOrderId(idWorker.nextId());
            order.setPaymentType(paymentType);
            order.setStatus("1");
            order.setUserId(userVO.getUsername());
            order.setReceiverAreaName(address.getAddress());
            order.setReceiverMobile(address.getMobile());
            order.setReceiver(address.getContact());
            order.setSellerId(cartVO.getSeller());
            order.setOut_trade_no(idWorker.nextId()+"");

            BigDecimal totalMoney = new BigDecimal(0);
            for (DetailVO detailVO : cartVO.getDetailVOS()) {
                totalMoney = totalMoney.add(detailVO.getTotalFee());
                payMoney = payMoney.add(detailVO.getTotalFee());
                sb.append(detailVO.getTitle());


                //创建订单明细
                TbOrderItem item = new TbOrderItem();
                item.setId(idWorker.nextId());
                item.setItemId(detailVO.getItemId());
                item.setGoodsId(detailVO.getGoodsId());
                item.setOrderId(order.getOrderId());
                item.setTitle(detailVO.getTitle());
                item.setPrice(detailVO.getPrice());
                item.setNum(detailVO.getNum());
                item.setTotalFee(detailVO.getTotalFee());
                item.setPicPath(detailVO.getPicPath());
                item.setSellerId(order.getSellerId());
                item.setOut_trade_no(order.getOut_trade_no());
                items.add(item);

                TbItem tbItem = new TbItem();
                tbItem.setId(item.getItemId());
                tbItem.setStockCount(item.getNum());

                counts.add(tbItem);

            }
            order.setPayment(totalMoney);
            orders.add(order);
        }

        //扣减库存
        itemAPI.updateStockQuantities(counts);

        //批量增加
        tbOrderMapper.insertBatch(orders);
//        int qwe = 1/0;
        tbOrderItemMapper.insertBatch(items);

        //清空购物车(作业)
        cartAPI.clearCatList(claims.getId());

        //组装支付用到的三个参数
        PayVo payVo = new PayVo();

        //订单编号赋值
        payVo.setOut_trade_no(idWorker.nextId()+"");
        //支付价格赋值
        payVo.setTotal_amount(payMoney.toString());
        //标题赋值
        payVo.setSubject(sb.toString());



        return payVo;
    }

    @Override
    public void updateBatch(ArrayList<String> orderNo, String tradeNo) {
        /*for (String s : orderNo) {
        }*/

    }
}
